package com.da.springtest.condition;

import java.util.Map;

import com.da.springtest.condition.test1.MainConfig1;
import com.da.springtest.condition.test2.BeanConfig;
import com.da.springtest.condition.test2.IService;
import com.da.springtest.condition.test3.EnvConfig;
import com.da.springtest.condition.test3.MainConfig3;
import com.da.springtest.condition.test4.MainConfig4;
import com.da.springtest.condition.test5.MainConfig5;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author chenlida
 * @date 2020/6/22 14:35
 *
 * 1.@Conditional注解可以标注在spring需要处理的对象上（配置类、@Bean方法），相当于加了个条件判断，通过判断的结果，
 * 让spring觉得是否要继续处理被这个注解标注的对象
 * 2.spring处理配置类大致有2个过程：解析配置类、注册bean，这两个过程中都可以使用@Conditional来进行控制spring是否需要处理这个过程
 * 3.Condition默认会对2个过程都有效
 * 4.ConfigurationCondition控制得更细一些，可以控制到具体那个阶段使用条件判断
 */
public class TestMethod {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig1.class);
        Map<String, String> serviceMap = context.getBeansOfType(String.class);
        show(serviceMap);
        System.out.println("------------------");
        AnnotationConfigApplicationContext context2 = new AnnotationConfigApplicationContext(BeanConfig.class);
        Map<String, IService> serviceMap2 = context2.getBeansOfType(IService.class);
        show(serviceMap2);
        System.out.println("------------------");
        AnnotationConfigApplicationContext envContext = new AnnotationConfigApplicationContext(EnvConfig.class);
        System.out.println(envContext.getBean(EnvConfig.class).getEnv());
        AnnotationConfigApplicationContext context3 = new AnnotationConfigApplicationContext(MainConfig3.class);
        System.out.println(context3.getBean("name"));
        System.out.println("------------------");
        new AnnotationConfigApplicationContext(MainConfig4.class);
        System.out.println("------------------");
        AnnotationConfigApplicationContext context5 = new AnnotationConfigApplicationContext(MainConfig5.class);
        Map<String, String> serviceMap5 = context5.getBeansOfType(String.class);
        show(serviceMap5);
    }

    private static void show(Map serviceMap) {
        serviceMap.forEach((beanName, bean) -> System.out.println(String.format("%s->%s", beanName, bean)));
    }

    private static void show(AnnotationConfigApplicationContext context) {
        for (String beanName : context.getBeanDefinitionNames()) {
            System.out.println(String.format("%s->%s", beanName, context.getBean(beanName)));
        }
    }
}
